package com.freejava.test_rocketmq.service;

import com.freejava.test_rocketmq.entity.MyMessage;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service
public class RocketMQService implements BaseRocketMQTool {
    // 引入日志类
    private static final Logger logger = LoggerFactory.getLogger(RocketMQService.class);

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void sendMsg(MyMessage myMessage) {
        // 记录日志信息
        logger.info("同步方式发送消息到MQ里面,消息是：{}", myMessage);
        // 发送消息
        rocketMQTemplate.send(myMessage.getTopic() + "->" + myMessage.getTags(),
                MessageBuilder.withPayload(myMessage.getContent()).build());
    }

    @Override
    public void asyncSendMsg(MyMessage myMessage) {
        // 记录日志信息
        logger.info("异步方式发送消息到MQ里面,消息是：{}", myMessage);
        // 发送消息
        rocketMQTemplate.asyncSend(myMessage.getTopic() + "->" + myMessage.getTags(), myMessage.getContent(),
                new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        // 成功不做日志记录或处理
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        logger.info("myMessage is {}, 消息发送失败啦", myMessage);
                    }
                });
    }
}
